package com.sky.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.dto.CreateOrderDTO;
import com.sky.dto.OrderPageQueryDTO;
import com.sky.dto.OrderStatusDTO;
import com.sky.entity.Order;
import com.sky.mapper.OrderMapper;
import com.sky.result.PageResult;
import com.sky.entity.Merchant;
import com.sky.entity.Student;
import com.sky.service.OrderService;
import com.sky.service.StudentService;
import com.sky.service.MerchantService;
import com.sky.vo.OrderVO;
import com.sky.vo.StudentVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.math.BigDecimal;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    
    private static final Logger log = LoggerFactory.getLogger(OrderServiceImpl.class);
    
    @Autowired
    private StudentService studentService;
    
    @Autowired
    private MerchantService merchantService;
    @Override
    public IPage<OrderVO> getOrderList(IPage<Order> page, Long studentId, String status) {
        IPage<Order> orderPage = baseMapper.selectByStudentId(page, studentId);
        // 转换为VO
        return orderPage.convert(order -> {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order, orderVO);
            return orderVO;
        });
    }

    @Override
    public OrderVO getOrderDetail(String orderNo) {
        Order order = baseMapper.selectByOrderNo(orderNo);
        if (order == null) {
            return null;
        }
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order, orderVO);
        return orderVO;
    }

    @Override
    public String createOrder(CreateOrderDTO createOrderDTO) {
        // 生成订单号
        String orderNo = generateOrderNo();
        Order order = new Order();
        order.setOrderNo(orderNo);
        order.setStudentId(createOrderDTO.getStudentId());
        // 计算订单总金额
        java.math.BigDecimal totalAmount = java.math.BigDecimal.ZERO;
        for (CreateOrderDTO.OrderItemDTO item : createOrderDTO.getItems()) {
            totalAmount = totalAmount.add(new java.math.BigDecimal(item.getUnitPrice()).multiply(new java.math.BigDecimal(item.getQuantity())));
        }
        order.setAmount(totalAmount);
        order.setStatus("pending");
        order.setOrderTime(LocalDateTime.now());
        // 保存订单
        baseMapper.insert(order);
        // 这里应该还有保存订单项的逻辑
        return orderNo;
    }

    @Override
    public void cancelOrder(String orderNo) {
        Order order = baseMapper.selectByOrderNo(orderNo);
        if (order != null && "pending".equals(order.getStatus())) {
            baseMapper.cancelOrder(order.getId());
        }
    }

    @Override
    public OrderVO getOrderById(Long id) {
        Order order = baseMapper.selectById(id);
        if (order == null) {
            return null;
        }
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order, orderVO);
        
        // 查询学生名称和联系电话
        try {
            if (order.getStudentId() != null) {
                StudentVO student = studentService.getStudentById(order.getStudentId());
                if (student != null) {
                    orderVO.setStudentName(student.getName());
                    orderVO.setContact(student.getContact());
                }
            }
        } catch (Exception e) {
            log.error("查询学生信息失败", e);
        }
        
        // 查询商家名称
        try {
            if (order.getMerchantId() != null) {
                Merchant merchant = merchantService.getById(order.getMerchantId());
                if (merchant != null) {
                    orderVO.setMerchantName(merchant.getName());
                }
            }
        } catch (Exception e) {
            log.error("查询商家信息失败", e);
        }
        
        return orderVO;
    }

    // 生成订单号
    private String generateOrderNo() {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String dateTime = LocalDateTime.now().format(formatter);
        Random random = new Random();
        int randomNum = 1000 + random.nextInt(9000); // 生成4位随机数
        return dateTime + randomNum;
    }

    @Override
    public PageResult adminPageQuery(OrderPageQueryDTO queryDTO) {
        // 创建分页对象
        Page<Order> page = new Page<>(queryDTO.getPage(), queryDTO.getPageSize());
        
        // 构建查询参数
        Map<String, Object> params = new HashMap<>();
        params.put("status", queryDTO.getStatus());
        params.put("orderNo", queryDTO.getOrderNo());
        params.put("studentId", queryDTO.getStudentId());
        params.put("merchantId", queryDTO.getMerchantId());
        params.put("studentName", queryDTO.getStudentName());
        params.put("merchantName", queryDTO.getMerchantName());
        params.put("startDate", queryDTO.getStartDate());
        params.put("endDate", queryDTO.getEndDate());
        
        // 执行分页查询
        IPage<Order> orderPage = baseMapper.selectByAdminQuery(page, params);
        
        // 转换为VO列表
        List<OrderVO> orderVOList = orderPage.getRecords().stream().map(order -> {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order, orderVO);
            
            // 设置学生名称
            if (order.getStudentId() != null) {
                try {
                    StudentVO student = studentService.getStudentById(order.getStudentId());
                    if (student != null) {
                        orderVO.setStudentName(student.getName());
                    }
                } catch (Exception e) {
                    // 处理异常，避免影响主流程
                }
            }
            
            // 设置商家名称
            if (order.getMerchantId() != null) {
                try {
                    Merchant merchant = merchantService.getById(order.getMerchantId());
                    if (merchant != null) {
                        orderVO.setMerchantName(merchant.getName());
                    }
                } catch (Exception e) {
                    // 处理异常，避免影响主流程
                }
            }
            
            return orderVO;
        }).collect(java.util.stream.Collectors.toList());
        
        // 构建返回结果
        PageResult pageResult = new PageResult();
        pageResult.setTotal(orderPage.getTotal());
        pageResult.setRecords(orderVOList);
        
        return pageResult;
    }

    @Override
    public void updateOrderStatus(OrderStatusDTO orderStatusDTO) {
        Order order = baseMapper.selectById(orderStatusDTO.getId());
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        
        // 更新订单状态
        order.setStatus(orderStatusDTO.getStatus());
        
        // 如果是完成订单，设置完成时间
        if ("已完成".equals(orderStatusDTO.getStatus())) {
            order.setCompleteTime(LocalDateTime.now());
        }
        
        // 更新订单
        baseMapper.updateById(order);
    }

    @Override
    public Map<String, Object> getOrderStats() {
        Map<String, Object> stats = new HashMap<>();
        
        // 获取总订单数
        Long totalOrders = baseMapper.selectCount(null);
        
        // 获取待处理订单数（待支付+待配送）
        Map<String, Object> pendingParams = new HashMap<>();
        List<String> statusList = new ArrayList<>();
        statusList.add("待支付");
        statusList.add("待配送");
        pendingParams.put("statusList", statusList);
        Long pendingOrders = baseMapper.selectCountByStatus(pendingParams);
        
        // 获取已完成订单数
        Map<String, Object> completedParams = new HashMap<>();
        completedParams.put("status", "已完成");
        Long completedOrders = baseMapper.selectCountByStatus(completedParams);
        
        // 获取已取消订单数
        Map<String, Object> cancelledParams = new HashMap<>();
        cancelledParams.put("status", "已退款");
        Long cancelledOrders = baseMapper.selectCountByStatus(cancelledParams);
        
        // 计算今日新增订单数
        LocalDateTime todayStart = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0);
        LocalDateTime todayEnd = LocalDateTime.now();
        Map<String, Object> todayParams = new HashMap<>();
        todayParams.put("startDate", todayStart);
        todayParams.put("endDate", todayEnd);
        // 添加orderTime条件，确保查询订单时间在今日范围内
        todayParams.put("dateField", "order_time");
        Long todayOrders = baseMapper.selectCountByDateRange(todayParams);
        
        // 计算总销售额
        BigDecimal totalAmount = baseMapper.selectTotalAmount();
        
        // 计算今日销售额
        Map<String, Object> todayAmountParams = new HashMap<>();
        todayAmountParams.put("startDate", todayStart);
        todayAmountParams.put("endDate", todayEnd);
        // 添加orderTime条件，确保查询订单时间在今日范围内
        todayAmountParams.put("dateField", "order_time");
        BigDecimal todayAmount = baseMapper.selectTotalAmountByDateRange(todayAmountParams);
        
        // 构建返回结果
        stats.put("totalOrders", totalOrders);
        stats.put("pendingOrders", pendingOrders);
        stats.put("completedOrders", completedOrders);
        stats.put("cancelledOrders", cancelledOrders);
        stats.put("todayOrders", todayOrders);
        stats.put("totalAmount", totalAmount);
        stats.put("todayAmount", todayAmount);
        
        return stats;
    }
    
    // 根据商家ID获取订单列表
    public IPage<OrderVO> getOrdersByMerchantId(Long merchantId, int page, int size) {
        IPage<Order> orderPage = new Page<>(page, size);
        orderPage = baseMapper.selectByMerchantId(orderPage, merchantId);
        
        // 转换为VO
        return orderPage.convert(order -> {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order, orderVO);
            
            // 查询学生信息
            if (order.getStudentId() != null) {
                try {
                    StudentVO student = studentService.getStudentById(order.getStudentId());
                    if (student != null) {
                        orderVO.setStudentName(student.getName());
                        orderVO.setContact(student.getContact());
                    }
                } catch (Exception e) {
                    log.error("查询学生信息失败，学生ID：{}", order.getStudentId(), e);
                }
            }
            
            // 查询商家信息
            if (order.getMerchantId() != null) {
                try {
                    Merchant merchant = merchantService.getById(order.getMerchantId());
                    if (merchant != null) {
                        orderVO.setMerchantName(merchant.getName());
                    }
                } catch (Exception e) {
                    log.error("查询商家信息失败，商家ID：{}", order.getMerchantId(), e);
                }
            }
            
            return orderVO;
        });
    }
}